package com.matou.commons.handler;


import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.matou.commons.constants.Resp;
import com.matou.commons.exception.BusinessException;
import com.matou.commons.exception.MtError;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * @Author CM
 * @Date 2021/5/9 10:55
 * @Description BaseExceptionHandler  通用业务异常处理
 * @Version 1.0
 */
@Slf4j
public class BaseExceptionHandler {
    /**
     * 处理系统未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Resp handleException(Exception e) {
        log.error("系统内部异常，异常信息", e);
        return Resp.failure(MtError.MT_999995);
    }

    /**
     * InvalidFormatException 异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({InvalidFormatException.class})
    public Resp<?> handleInvalidFormatException(Exception e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return Resp.failure(MtError.MT_999996);
    }

    /**
     * HttpMessageNotReadableException 异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Resp<?> handleHttpMessageNotReadableException(Exception e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return Resp.failure(MtError.MT_999996);
    }

//    /**
//     * 处理用户认证、登录异常
//     * @param e
//     * @return
//     */
//    @ExceptionHandler(value = CmAuthException.class)
//    public Resp handleFebsAuthException(CmAuthException e) {
//        log.error("系统错误", e);
//        return Resp.failure(e.getMessage());
//    }

    /**
     * 处理security 权限访问异常
     *
     * @return
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public Resp handleAccessDeniedException() {
        return Resp.failure(MtError.MT_001003);
    }

    /**
     * 处理通用业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Resp handleBusinessException(BusinessException e) {
        log.error("通用业务异常", e);
        return Resp.failure(MtError.MT_999998.getCode(),e.getMessage());
    }

    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return FebsResponse
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Resp handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return Resp.failure(MtError.MT_999997.getCode(), message.toString());
    }

    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return FebsResponse
     */
    @ExceptionHandler(BindException.class)
    public Resp handleBindException(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return Resp.failure(MtError.MT_999997.getCode(), message.toString());
    }
}
